package cn.kgc.boot.tcuser.controller;

import cn.kgc.boot.tcuser.entity.TcUser;
import cn.kgc.boot.tcuser.entity.UploadFile;
import cn.kgc.boot.tcuser.service.TcUserService;
import cn.kgc.boot.tcuser.service.UploadFileService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class TcUserController {

    @Autowired
    private TcUserService tcUserService;

    @Autowired
    private UploadFileService uploadFileService;

    private final String SESSION_USER = "loginUser";

    @Value("${file.upload-folder}")
    private String baseUrl;

    @RequestMapping(value = "loginUser", method = RequestMethod.POST)
    public String loginUser(TcUser tcUser, HttpSession session){
        TcUser tcUser1 = tcUserService.loginUser(tcUser);
        log.info("用户{}, 登录密码：{}尝试登录", tcUser.getUsername(), tcUser.getPassword());
        if(tcUser1!=null){
            session.setAttribute(SESSION_USER,tcUser1);
            return "welcomeUser";
        }else{
            return "view/index/index";
        }
    }

    /**
     *  退出登录
     * @param session
     * @return
     */
    @RequestMapping(value = "signOut", method = RequestMethod.GET)
    public String signOut(HttpSession session){
        session.removeAttribute(SESSION_USER);
        return "view/index/index";
    }

    @ResponseBody
    @RequestMapping(value = "ajaxGetFiles", method = RequestMethod.GET)
    public Map<String, Object> ajaxGetFiles(String nameOrTitle){
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", -1);
        map.put("msg", "没有找到该数据");
        List<UploadFile> uploadFiles = uploadFileService.queryAllUpLoadFile(nameOrTitle);
        log.info("查询所有下载文件信息：{}", JSON.toJSONString(uploadFiles));
        if (!uploadFiles.isEmpty()){
            map.put("code", 1);
            map.put("data", uploadFiles);
        }
        return map;
    }

    @RequestMapping(value = "toLogin", method = RequestMethod.GET)
    public String toLogin(){
        return "view/index/index";
    }

    @RequestMapping(value = "download", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response, String[] url, String name, Integer fileId) {
        //前端页面将自己需要的文件名字拿过来。这个名字直接拼接到文件所在服务器的相对路径。这里为便于测试。我直接把名字写死，以后使用的时候
        //根据实际业务进行修改。
//        String fileName = request.getParameter("file");
        String collect = String.join("/", url);
        log.info("下载文件路径:{}, 文件名称:{}", collect, name);
        System.out.println(baseUrl);
        try {
//            String path = "C:\\Users\\HASEE\\Desktop\\aaa\\Adobe Photoshop CC.zip";
            String path = baseUrl + collect;
            //这里是下载以后的文件叫做什么名字。我这里是以时间来定义名字的。
            downCfg(name, request, response);
            OutputStream out;
            FileInputStream inputStream = new FileInputStream(path);
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            inputStream.close();
            out.close();
            out.flush();
            log.info("下载完成");
            int i = uploadFileService.updateDownloadCount(fileId);
            log.info(i > 0 ? "Id为{}文件名称为{}下载成功记录下载次数+1" : "Id为{}文件名称为{}下载成功记录下载次数失败", fileId, name);
        } catch (IOException e) {
            log.error("下载失败", e);
        }

    }



    private void downCfg(String fileName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 判断浏览器，进行不同的加密，这样下载的时候保存的文件名就不会乱码
        String userAgent = request.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
    }



}
